package com.spring.boot.demo.config;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.boot.autoconfigure.SpringBootVFS;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
 * @author ZhuYouBin
 * @version 1.0.0
 * @Date: 2022/10/26 22:16
 * @Description
 */
@MapperScan(
        basePackages = "com.spring.boot.demo.master.mapper",
        sqlSessionFactoryRef = "masterSqlSessionFactory",
        sqlSessionTemplateRef = "masterSqlSessionTemplate"
)
@Configuration
public class MasterDataSourceConfig {

    // 默认指定 master 作为主数据源
    @Primary
    // 注入数据源
    @Bean("masterDataSource")
    // 指定 master 数据源的配置信息前缀
    @ConfigurationProperties(prefix = "spring.datasource.master")
    public DataSource masterDataSource() {
        // 手动创建 Druid 数据源对象
        return DruidDataSourceBuilder.create().build();
    }

    // 创建 SqlSessionFactory 对象
    @Bean("masterSqlSessionFactory")
    public SqlSessionFactory masterSqlSessionFactory(@Qualifier("masterDataSource") DataSource masterDataSource) throws Exception {
        // 创建 SqlSessionFactoryBean 对象
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        // 设置数据源
        factoryBean.setDataSource(masterDataSource);
        // 设置 mapper 映射文件路径
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        factoryBean.setMapperLocations(resolver.getResources("classpath:mappers/master/**/*.xml"));
        // 设置 VFS
        factoryBean.setVfs(SpringBootVFS.class);
        // 返回 SqlSessionFactory 对象
        return factoryBean.getObject();
    }

    // 创建 SqlSessionTemplate 对象
    @Bean("masterSqlSessionTemplate")
    public SqlSessionTemplate masterSqlSessionTemplate(@Qualifier("masterSqlSessionFactory") SqlSessionFactory masterSqlSessionFactory) {
        // 创建 SqlSessionTemplate 对象
        return new SqlSessionTemplate(masterSqlSessionFactory);
    }

}
